package com.yoomiito.app.widget.dialog

import android.graphics.drawable.GradientDrawable
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.alibaba.fastjson.JSONObject
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.yoomiito.app.*
import com.yoomiito.app.adapter.dialog.CommentAdapter
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.BaseList
import com.yoomiito.app.model.comment.Comment
import com.yoomiito.app.model.comment.CommentInfo
import com.yoomiito.app.model.home.VideoClipInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.utils.DensityUtil
import com.yoomiito.app.utils.EventMessage
import com.yoomiito.app.utils.L
import com.yoomiito.app.utils.Type
import com.yoomiito.app.widget.SpacingDecoration
import io.reactivex.Observable
import kotlinx.android.synthetic.main.item_video_clip_bottom.view.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CommentDialog(val context: BaseActivity<*>, val videoInfo: VideoClipInfo?,var onCommentResultListener:(Int)->Unit) : BaseDialog(context, R.style.custom_dialog) {

    private var mRecyclerView: androidx.recyclerview.widget.RecyclerView? = null
    private var smartRefreshLayout: SmartRefreshLayout? = null
    private var title: TextView? = null
    private var mCurrentPage = 1
    private val datas = mutableListOf<Comment>()
    private val mAdapter = CommentAdapter(context, datas)
    private val ids = mutableListOf<String>()
    private var mClickPosition = 0//拉起评论弹窗的位置
    private var commentSize = 0
    override fun setView(): View {
        window?.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_comment, null, false)
        smartRefreshLayout = view.findViewById(R.id.smartRefreshLayout)
        smartRefreshLayout?.setEnableRefresh(false)
        smartRefreshLayout?.setOnLoadMoreListener {
            mCurrentPage++
            commentList(mCurrentPage)
        }
        view.findViewById<View>(R.id.cancelLl).setOnClickListener { dismiss() }
        mRecyclerView = view.findViewById(R.id.rcy)
        title = view.findViewById<TextView>(R.id.titleTv)
        title?.text = "共${videoInfo?.videoOtherInfo?.comment_num?.formatNum()}条评论"
        view.findViewById<ImageView>(R.id.close).setOnClickListener { dismiss() }
        val inputTipTv = view.findViewById<TextView>(R.id.inputTipTv)
        val drawable = inputTipTv.background as GradientDrawable
        drawable.cornerRadius = DensityUtil.dp2px(16f).toFloat()
        val lp = view.findViewById<LinearLayout>(R.id.dialogLl).layoutParams as LinearLayout.LayoutParams
        lp.height = (App.mHeightPx * 0.68).toInt()

        view.findViewById<View>(R.id.inputComment).setOnClickListener {
            inputComment(videoInfo?.id!!, "1", "")
        }
        mRecyclerView?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
        mRecyclerView?.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator()
        mRecyclerView?.addItemDecoration(SpacingDecoration(0, DensityUtil.dp2px(16f), true))
        mRecyclerView?.adapter = mAdapter
        mAdapter.onItemClickListener = {
            mClickPosition = it
            val comment = datas[it]
            inputComment(comment.id, "2", comment.nickName)
        }
        mAdapter.onLikeClickListener = {
            val comment = datas[it]
            L.i("点赞：$it   ${comment.commentContent}")
            videoLike(comment, it)
        }
        setmHeightPercent((-1).toDouble())
        setWidthPercent(1.toDouble())
        setmGravity(Gravity.BOTTOM)
        setCanceledOnTouchOutside(true)
        return view
    }

    private fun videoLike(comment: Comment, position: Int) {
        YmApi.getYmService()
                .videoCommentLike(comment.id)
                .compose(context.bindToLifecycle())
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>>() {
                    override fun onSuccess(t: BaseModel<*>?) {
                        comment.isLike = if (comment.isLike == 0) 1 else 0
                        comment.likeNumber = if (comment.isLike == 1) (comment.likeNumber.toInt() + 1).toString() else (comment.likeNumber.toInt() - 1).toString()
                        mAdapter.notifyItemChanged(position)
                    }

                    override fun onFail(error: ApiException?) {
                        error?.msg?.strFilter { it.isNullOrEmpty() }.let { it?.showToast() }
                    }

                })
    }

    fun showDialog() {
        commentList(mCurrentPage)
    }

    /**
     * @param type 1 回复视频  2 回复评论
     */
    private fun inputComment(id: String, type: String, nickName: String) {
        val comment = InputCommentDialog(context, id, type, nickName)
        comment.onMessageListener = { comment, show ->
            if (show) {
                dismiss()
            } else {
                //需求：主评论显示在最顶部，二级评论要插入到其在主评论的所有二级评论的最后位置
                //查找评论要插入的位置
                // type为1 时 表示评论的视频 直接在0处插入数据 然后滚动到0
                // type不为1 时 表示评论的评论 也就是二级评论  就需要找到要插入的位置
                // 插入位置查询：调起输入评论框时记录了要回复的评论的位置，然后从这个位置开始往后查找，直到查到下一条主评论(也就是type=1)的位置为止，
                //             然后在该位置插入数据 然后滚动到该位置
                var p = 0
                if (comment.type != 1) {
                    var hasNext = false//是否有下一个主评论
                    if (mClickPosition != datas.size) {//如果点击的不是最后一个 则往下查找位置  否则 直接在最后添加
                        for (index in (mClickPosition + 1) until datas.size) {
                            if (datas[index].type == 1) {
                                p = index
                                hasNext = true
                                break
                            }
                        }
                    }

                    if (!hasNext) {
                        p = datas.size
                    }
                }
                datas.add(p, comment)
                commentSize += 1
                showCommentSize()
                mAdapter.notifyItemInserted(p)
                mAdapter.notifyItemRangeChanged(p+1 , datas.size-(p+1))
                mRecyclerView?.scrollToPosition(p)
            }
        }
        comment.show()
    }

    private fun commentList(page: Int) {
        YmApi.getYmService()
                .commentList(videoInfo?.id, page)
                .compose(context.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<BaseList<CommentInfo>>() {
                    override fun onSuccess(t: BaseList<CommentInfo>?) {
                        commentSize = t?.count?.toInt()!!
                        if (t?.current_page!! > t?.last_page!!) {
                            smartRefreshLayout?.finishLoadMoreWithNoMoreData()
                        } else {
                            smartRefreshLayout?.finishLoadMore()
                            showCommentList(t.data)
                            mCurrentPage = t?.current_page
                            if (!isShowing) {
                                show()
                            }
                        }
                        showCommentSize()
                    }

                    override fun onFail(error: ApiException?) {
                        error?.msg?.showToast()
                    }

                })
    }

    /**
     * 修改当前评论总数量 并通知视频详情评论数量改变
     */
    private fun showCommentSize(){
        title?.text = "共${commentSize.toString()}条评论"
        onCommentResultListener(commentSize)
    }

    private fun showCommentList(infos: List<CommentInfo>) {
        Observable.fromIterable(infos)
                .filter { !ids.contains(it.commentId) }
                .subscribe { it ->
                    val comment = Comment()
                    comment.id = it.commentId
                    comment.nickName = it.nickName
                    comment.headUrl = it.headUrl
                    comment.commentContent = it.commentContent
                    comment.isLike = it.isLike
                    comment.likeNumber = it.likeNumber
                    comment.time = it.time
                    comment.replayName = it.replayName
                    comment.isReplay = it.isReplay
                    comment.type = 1//1 一级评论 2 二级评论
                    datas.add(comment)
                    ids.add(it.commentId)
                    if (it.childComment != null) {
                        it.childComment.forEach { i ->
                            val comment = Comment()
                            comment.id = i.commentId
                            comment.nickName = i.nickName
                            comment.headUrl = i.headUrl
                            comment.commentContent = i.commentContent
                            comment.isLike = i.isLike
                            comment.likeNumber = i.likeNumber
                            comment.time = i.time
                            comment.replayName = i.replayName
                            comment.isReplay = i.isReplay
                            comment.type = 2//1 一级评论 2 二级评论
                            datas.add(comment)
                        }
                    }
                    mAdapter.notifyDataSetChanged()
                }

    }
}